package com.hm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hm.reggie.common.CustomException;
import com.hm.reggie.entity.*;
import com.hm.reggie.mapper.OrdersMapper;
import com.hm.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public void submit(Orders orders, HttpSession session) {
        //获取当前用户数据
        User user  = (User)session.getAttribute("user");
        Long userId = user.getId();
        //获取用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(userId != null,ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        if (shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空");
        }
        //查询购物车信息，计算金额
        Long orderId= IdWorker.getId();
        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //查询地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        String address = addressBook.getDetail();
        String consignee = addressBook.getConsignee();
        //获取用户姓名
        User user1 = userService.getById(userId);
        String username = user1.getName();
        //插入主表
        orders.setNumber(orderId+"");//订单号
        orders.setStatus(2);//订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);//下单用户
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//结账时间
        orders.setPhone(user1.getPhone());
        orders.setAddress(address);
        orders.setUserName(username);
        orders.setConsignee(consignee);
        orders.setAmount(new BigDecimal(amount.get()));

        this.save(orders);

        //插入子表
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.remove(queryWrapper);

    }
}
